<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>再访问内置的拖放操作</title>
    <style>
        [data-drop-target] {
            height: 400px;
            width: 200px;
            margin: 2px;
            background-color: gainsboro;
            float: left;
        }

        .drag-enter {
            border: 2px dashed #000;
        }

        .box {
            width: 200px;
            height: 200px;
        }

        .navy {
            background-color: navy;
        }

        .red {
            background-color: red;
        }
    </style>
    <script src="//cdn.bootcss.com/modernizr/2.8.3/modernizr.min.js"></script>
</head>
<body>
<div data-drop-target="true">
    <div class="box navy" id="box-1" draggable="true"></div>
    <div class="box red" id="box-2" draggable="true"></div>
</div>
<div data-drop-target="true"></div>
<script>
    function dragStartHandler(e) {
        e.dataTransfer.setData('text', this.id);
    }

    function dragEnterLeaveHandler(e) {
        if (e.type == 'dragenter') {
            this.className = 'drag-enter';
        } else {
            this.className = '';
        }
    }

    function overDrophandler(e) {
        e.preventDefault();
        if (e.type != 'drop') {
            return;
        }

        var draggedId = e.dataTransfer.getData('text');
        var draggedElement = document.getElementById(draggedId);

        if (draggedElement.parentNode == this) {
            this.className = '';
            return;
        }
        draggedElement.parentNode.removeChild(draggedElement);
        this.appendChild(draggedElement);
        this.className = '';
    }

    function init() {
        var draggable = document.querySelectorAll('[draggable]');
        var targets = document.querySelectorAll('[data-drop-target]');

        for (var i = 0; i < draggable.length; i++) {
            draggable[i].addEventListener('dragstart', dragStartHandler);
        }

        for (i = 0; i < targets.length; i++) {
            targets[i].addEventListener('dragover', overDrophandler);
            targets[i].addEventListener('drop', overDrophandler);
            targets[i].addEventListener('dragenter', dragEnterLeaveHandler);
            targets[i].addEventListener('dragleave', dragEnterLeaveHandler);
        }
    }

    Modernizr.addTest('draggable', function () {
        var elem = document.createElement('span');
        return typeof elem.draggable != 'undefined';
    });

    Modernizr.load([
        {
            test: Modernizr.draggable,
            nope: 'draggable-polyfill.js'
        },
        {
            test: document.addEventListener,
            nope: 'event-polyfill.js',
            complete: init
        }
    ]);
</script>
</body>
</html>